package com.exp.sys.action;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import tk.mybatis.mapper.entity.Example;

import com.alibaba.druid.support.json.JSONUtils;
import com.exp.base.action.DataTablesPage;
import com.exp.base.action.DataTablesPageInfo;
import com.exp.base.action.EasyuiPage;
import com.exp.base.action.EasyuiPageInfo;
import com.exp.base.action.Message;
import com.exp.base.util.BeanUtils;
import com.exp.base.util.CacheUtils;
import com.exp.sys.entity.Admin;
import com.exp.sys.entity.Role;
import com.exp.sys.service.AdminService;
import com.exp.sys.service.RoleService;
import com.exp.sys.vo.admin.AdminVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.primitives.Booleans;

@Controller
@RequestMapping("/sys/admin")
public class AdminAction extends BaseAction {
	@Resource
	AdminService adminDomain;
	
	@Resource
	RoleService roleDomain;
	
	@RequestMapping("add")
	public String add(Model model){
		final AdminVo admin = new AdminVo();
		model.addAttribute("admin", admin);
		Example roleExample = new Example(Role.class);
		roleExample.createCriteria().andEqualTo("deleted", false);
		List<Role> roleList = roleDomain.query(roleExample);
		
		List<Map<String, Object>> _roleList = Lists.transform(roleList, new Function<Role, Map<String,Object>>() {
			@Override
			public Map<String, Object> apply(Role role) {
				Map<String, Object> map = BeanUtils.beanToMap(role);
				map.put("selected", (admin.getRoleIdList().contains(role.getId())?true:false));
				return map;
			}
		});
		model.addAttribute("roleList", _roleList);
		return "sys/admin/admin_input";
	}
	
	@RequestMapping("edit")
	public String edit(Model model,@ModelAttribute("id") String id){
		final AdminVo admin = adminDomain.getVo(id);
		model.addAttribute("admin", admin);
		final Example roleExample = new Example(Role.class);
		roleExample.createCriteria().andEqualTo("deleted", false);
		List<Role> roleList = roleDomain.query(roleExample);
		List _roleList = Lists.transform(roleList, new Function<Role,Map>(){
			@Override
			public Map apply(Role role) {
				Map map = new HashMap(new BeanMap(role));
				map.put("selected", (admin.getRoleIdList().contains(role.getId())?true:false));
				return map;
			}
			
		});
		
		model.addAttribute("roleList", _roleList);
		return "sys/admin/admin_input";
	}
	
	@RequestMapping("list")
	public String list(){
		return "sys/admin/admin_list";
	}
	
	@ResponseBody
	@RequestMapping(value="save")
	public Message save(HttpServletRequest request,AdminVo admin){
		List<String> errors = new ArrayList<String>();
		if(isValid(admin, errors)){
		}
		if(StringUtils.isEmpty(admin.getPassword())){
			errors.add("密码不能为空");
		}
		if(errors.isEmpty()){
			Example example = new Example(Admin.class);
			example.createCriteria().andEqualTo("name", admin.getName());
			if(adminDomain.exist(example)){
				errors.add(StringUtils.join(admin.getName(),"已存在",(admin.isDeleted()?"（回收站）":"")));
			};
		}
		
		if(errors.isEmpty()){
			admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
			adminDomain.saveVo(admin);
			return new Message(true);
		}
		return new Message(false,StringUtils.join(errors,","));
	}
	
	@ResponseBody
	@RequestMapping(value="update")
	public Message update(HttpServletRequest request,AdminVo admin){
		List<String> errors = new ArrayList<String>();
		if(isValid(admin, errors)){
			AdminVo adminEntity = adminDomain.getVo(admin.getId());
			filterParameterMapMore(request, admin, adminEntity, "roleIdList");
			if(StringUtils.isNotEmpty(admin.getPassword())){
				String passwdMd5 = DigestUtils.md5Hex(admin.getPassword());
				adminEntity.setPassword(passwdMd5);
			}
			adminDomain.updateVo(adminEntity);
			return new Message(true);
		}else{
			return new Message(false,StringUtils.join(errors,","));
		}
	}
	
	@ResponseBody
	@RequestMapping(value="delete")
	public Message delete( String[] ids){
		adminDomain.deleteWithRelate(ids);
		return new Message(true);
	}
	
	@ResponseBody
	@RequestMapping(value="softDelete")
	public Message softDelete( String[] ids){
		adminDomain.softDelete(ids);
		return new Message(true);
	}
	
	@ResponseBody
	@RequestMapping("query")
	public EasyuiPageInfo query(Model model,EasyuiPage easyuiPage){
//		Page<Admin> page = new Page<Admin>(easyuiPage.getPage(), easyuiPage.getRows());
//		HashMap<String, Object> map = new HashMap<String, Object>(){{
//			put("deleted",false);
//		}};
//		PageInfo<Admin> pageInfo = adminDomain.query(page,map);
		
		Page<Admin> page = new Page<Admin>(easyuiPage.getPage(), easyuiPage.getRows());
		Example example = new Example(Admin.class);
		example.createCriteria().andEqualTo("deleted", false);
		example.setOrderByClause("create_date desc");
		PageInfo<Admin>  pageInfo = adminDomain.query(example, page);
		EasyuiPageInfo easyuiPageInfo = new EasyuiPageInfo(pageInfo);
		return easyuiPageInfo;
	}
	
	@ResponseBody
	@RequestMapping("queryRecycle")
	public EasyuiPageInfo queryRecycle(Model model,EasyuiPage easyuiPage){
		Page<Admin> page = new Page<Admin>(easyuiPage.getPage(), easyuiPage.getRows());
		Example example = new Example(Admin.class);
		example.createCriteria().andEqualTo("deleted", true);
		example.setOrderByClause("create_date desc");
		PageInfo<Admin> pageInfo = adminDomain.query(example, page);
		EasyuiPageInfo easyuiPageInfo = new EasyuiPageInfo(pageInfo);
		return easyuiPageInfo;
	}
	
	
	@ResponseBody
	@RequestMapping("test")
	public java.sql.Date test(java.sql.Date time){
		System.out.println(time);
		return time;
	}
	
	
	
}
